/*
 * Copyright (C) 2012 yueyueniao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wzm.moviepic.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.wzm.bean.DownInfo;
import com.wzm.bean.MovieInfo;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.Tag;
import com.wzm.moviepic.AppApplication;
import com.wzm.moviepic.R;
import com.wzm.moviepic.slidingmenu.Main1Activity;
import com.wzm.utils.ActivityTools;
import com.wzm.utils.FileUtils;
import com.wzm.utils.Logger;
/**
 * 左侧
 * @author Administrator
 *
 */
public class LeftFragment extends Fragment {

	//private Button btn = null;
	private ListView downList = null;
	private DownAdapter da = null;
	private ArrayList<DownInfo> dList = null;
	private Context mContext = null;
	
	private LinearLayout lly_btn1,lly_btn2,lly_btn3,lly_btn4;
	private TextView tv_mcount,tv_cache;
	
	
	//手势
	private GestureDetector detector;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		mContext = getActivity();
		View view = inflater.inflate(R.layout.fragment_left, null);		
		
		dList = AppApplication.getInstance().getDownList();
		
		downList = (ListView)view.findViewById(R.id.downlist);		
		da = new DownAdapter(mContext,dList);
		downList.setAdapter(da);
		
		getDownList();
		
		
		downList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				DownInfo di = dList.get(arg2);
				MovieInfo mi = new MovieInfo();
				mi.setName(di.getMoviename());
				mi.setId(di.getMovieid());
				Intent intent = new Intent(mContext,ViewPagerActivity.class);			
				Bundle bundle = new Bundle();
				bundle.putSerializable("movieinfo", mi);
				intent.putExtras(bundle);
				mContext.startActivity(intent);
				intent = null;
				mi = null;
				
			}
		});
		
		
		
		
		detector = new GestureDetector(getActivity(),new OnGestureListener() {
			
			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onShowPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
					float distanceY) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onLongPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
					float velocityY) {
				// TODO Auto-generated method stub
				
				if (e1.getX() - e2.getX() > 120) {
					//Logger.info("向左...");
					((Main1Activity)mContext).showcenter();
		            return true;
		        } else if (e1.getX() - e2.getX() < -120) {
		        	{//本地资源页面
//		        		FragmentTransaction t = getActivity().getSupportFragmentManager()
//								.beginTransaction();
//						t.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
//						LocalFileFragment page2 = new LocalFileFragment();
//						t.replace(R.id.left_frame, page2);
//						t.commit();
//						page2 = null;
		        	}
		            return true;
		        }
				
				return false;
			}
			
			@Override
			public boolean onDown(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		
		downList.setOnTouchListener(new OnTouchListener() {
		
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return detector.onTouchEvent(event);
			}
		});
	
		
		tv_mcount = (TextView)view.findViewById(R.id.tv_mcount);
		tv_mcount.setText("我们都懂");
		tv_cache = (TextView)view.findViewById(R.id.tv_cache);
		tv_cache.setText(getLocalCache());
		
		
		
		//注册下载更新广播
		IntentFilter intentFilter = new IntentFilter(Tag.UPDATEUI);
		getActivity().registerReceiver( uiBroadcastReceiver , intentFilter); 
		intentFilter = null;
		
		lly_btn1 = (LinearLayout)view.findViewById(R.id.lly_btn1);
		lly_btn1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				ActivityTools.openQiuPian(mContext);
//				跳转到下载页面				
//				FragmentTransaction t = getActivity().getSupportFragmentManager()
//						.beginTransaction();
//				t.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
//				LocalFileFragment page2 = new LocalFileFragment();
//				t.replace(R.id.left_frame, page2);
//				t.commit();
//				page2 = null;
			}
		});
		lly_btn2 = (LinearLayout)view.findViewById(R.id.lly_btn2);
		lly_btn2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//清除缓存
//				File file = new File(Environment.getExternalStorageDirectory().getPath()+AppConfig.IMGCACHE);
//				FileUtils.deleteDir(file);
//				file = null;
//				Toast.makeText(getActivity(), "清除完成,部分缓存图片可能无法显示，请重启APP", Toast.LENGTH_SHORT).show();
				//tv_cache.setText("0.00K");
				showDelConfig(getActivity());
			}
		});
		lly_btn3 = (LinearLayout)view.findViewById(R.id.lly_btn3);
		lly_btn3.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FragmentTransaction t = getActivity().getSupportFragmentManager()
						.beginTransaction();
				t.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
				AboutUsFragment page2 = new AboutUsFragment();
				t.replace(R.id.left_frame, page2);
				t.commit();
				page2 = null;
			}
		});
		lly_btn4 = (LinearLayout)view.findViewById(R.id.lly_btn4);
		lly_btn4.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FragmentTransaction t = getActivity().getSupportFragmentManager()
						.beginTransaction();
				t.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
				SystemFragment page2 = new SystemFragment();
				t.replace(R.id.left_frame, page2);
				t.commit();
				page2 = null;
			}
		});

		
		return view;
	}
	
	public void showDelConfig(final Context context) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder
            .setMessage("清除缓存？")
            .setPositiveButton("清除",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    	tv_cache.setText("0.00K");  	
                    }
                }
            ).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }
            );
        alertBuilder.create().show();
    }
	
	
	

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}
	
	public void getDownList()
	{
		dList.clear();
		Collection<DownInfo> c = AppApplication.getInstance().getDMap().values();
        Iterator<DownInfo> it = c.iterator();
        for (; it.hasNext();) {
        	DownInfo di = (DownInfo)it.next();
        	dList.add(di);
        }
		da.updateUI();
		AppApplication.getInstance().setDList(dList);
		
		int curMovieid = AppApplication.getInstance().getCurDownMovie();
		if(curMovieid==0&&dList.size()>0)
		{//启动下载
			Intent service = new Intent(Tag.START);
			service.putExtra("action", Tag.DownPicList);
			service.putExtra("movieid", dList.get(AppApplication.getInstance().getCurDownid()).getMovieid());
			//AppApplication.getInstance().setCurDownMovie(Integer.valueOf(dList.get(curDownid).getMovieid()));
		    mContext.startService(service);
		}
				
	}
	
	public int getSize()
	{
		int size = 0;
		Cursor cursor = DBHelper.getInstance(mContext).querySql("select * from downinfo where downTag = 1 order by id asc", null);
		if(null!=cursor&&cursor.getCount()>0)
		{
			//Logger.error("本地文件:"+cursor.getCount());
			size = cursor.getCount();
		}
		if(cursor!=null)
		{
			cursor.close();
		}
		return size;
	}
	
	
	

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		
		
		super.onResume();
	}
	
	
	
	
	@Override
	public void onDestroy() {
		mContext.unregisterReceiver(uiBroadcastReceiver);		
		super.onDestroy();
	}




	private BroadcastReceiver uiBroadcastReceiver = new BroadcastReceiver() 
	{
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equals(Tag.UPDATEUI))
			{
				//获取队列
				dList.clear();
//				Set<String> key = AppApplication.getInstance().getDMap().keySet();
//		        for (Iterator it = key.iterator(); it.hasNext();) {
//		        	DownInfo di = (DownInfo)it.next();
//		            //System.out.println(map.get(s));
//		        	dList.add(di);
//		        }
				Collection<DownInfo> c = AppApplication.getInstance().getDMap().values();
		        Iterator<DownInfo> it = c.iterator();
		        for (; it.hasNext();) {
		        	DownInfo di = (DownInfo)it.next();
		        	dList.add(di);
		        }
				da.updateUI();
				//AppApplication.getInstance().setDList(dList);				
				int curMovieid = AppApplication.getInstance().getCurDownMovie();
				if(curMovieid==0&&dList.size()>0)
				{//启动下载
					int curDownid = AppApplication.getInstance().getCurDownid();
					Logger.info("curDownid:"+curDownid);
					Intent service = new Intent(Tag.START);
					service.putExtra("action", Tag.DownPicList);
					service.putExtra("movieid", dList.get(curDownid).getMovieid());
					//AppApplication.getInstance().setCurDownMovie(Integer.valueOf(dList.get(curDownid).getMovieid()));
				    mContext.startService(service);				    
				    service = null;
				}else{
					if(dList.size()==0)
					{
						Intent service = new Intent(Tag.START);
						mContext.stopService(service);
						service = null;
					}
				}
				
				//tv_mcount.setText(getSize()+" 部");
				
			}			
		}		
	};
	
	
	public String getLocalCache()
	{
        File ff = new File(Environment.getExternalStorageDirectory().getPath()+AppConfig.IMGCACHE);		
        long filesize = 0;
		try {
			filesize = FileUtils.getFileSize(ff);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}		
		String filesizestr = FileUtils.FormetFileSize(filesize);
		return filesizestr;
	}
	
	
}
